package cn.bob.pet.consumer;

import cn.bob.order.domain.OrderPetAcquisition;
import cn.bob.order.domain.OrderPetAcquisitionLog;
import cn.bob.order.mapper.OrderPetAcquisitionLogMapper;
import cn.bob.order.mapper.OrderPetAcquisitionMapper;
import cn.bob.pet.domain.SearchMasterMsg;
import cn.bob.pet.mapper.SearchMasterMsgMapper;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author bob
 * @data 2022/11/7-12:40
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "queue_test_topic",selectorExpression="*",consumerGroup = "service-pay-producer")
public class RocketMQMsgListener implements RocketMQListener<MessageExt> {
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private OrderPetAcquisitionLogMapper orderPetAcquisitionLogMapper;

    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        String msg = new String(body, CharsetUtil.UTF_8);
        //将监听到的数据id转换未integer类型
        Long id = Long.valueOf(msg);
        //通过这个id查询信息
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.findById(id);
        //判断状态是否修改，也就是是否处理过 到时间没有处理就修改订单状态将petmsg的数据shopid置空
        if (orderPetAcquisition.getState()==0){
            orderPetAcquisition.setState(-1);
            orderPetAcquisitionMapper.update(orderPetAcquisition);
            SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(orderPetAcquisition.getSearchMasterMsgId());
            searchMasterMsg.setShopId(null);
            searchMasterMsg.setState(1);
            searchMasterMsgMapper.update(searchMasterMsg);

            //添加取消订单日志
            OrderPetAcquisitionLog orderPetAcquisitionLog = new OrderPetAcquisitionLog();
            orderPetAcquisitionLog.setFailtime(new Date());
            orderPetAcquisitionLog.setOrderId(id);
            orderPetAcquisitionLogMapper.add(orderPetAcquisitionLog);
            System.out.println("已经到时间上限了！！");
        }

        log.info("接收到消息：{}", msg);
        System.out.println("监听消费成功");
    }
}
